package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.errorprone.annotations.Var;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcMenu;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private XcUserMapper xcUserMapper;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    private XcMenuMapper xcMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //传入的请求认证参数是AuthParamsDto，先将传入的json转成AuthParamsDto对象
        AuthParamsDto authParamsDto = new AuthParamsDto();
        try {
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("请求认证参数不符合要求");
        }

        //认证类型，password或者wx
        String authType = authParamsDto.getAuthType();

        //根据认证方法，从容器中取出指定的bean
        String beanName = authType + "_authservice";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);

        //调用统一execute方法进行认证
        XcUserExt xcUserExt = authService.execute(authParamsDto);

        //将xcUserExt封装成userDetails对象
        //spring security框架根据UserDetails对象生成令牌
        UserDetails userDetails = getUserPrincipal(xcUserExt);
        return userDetails;
    }

    /**
     *  查询用户信息
     * @param xcUserExt
     * @return
     */
    private UserDetails getUserPrincipal(XcUserExt xcUserExt){
        //查到用户，拿到正确密码，封装成一个UserDetails对象返回给spring security，由框架比对密码
        //查询用户权限
        String[] authorities = {"test"};
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(xcUserExt.getId());
        if(xcMenus.size() > 0){
            List<String> permissions = new ArrayList<>();
            xcMenus.forEach(m -> {
                permissions.add(m.getCode());
            });

            //将permissions转成数组
            authorities = permissions.toArray(new String[0]);
        }

        //将user对象转json
        String userString = JSON.toJSONString(xcUserExt);

        //创建UserDetails对象
        UserDetails userDetails = User.withUsername(userString).password(xcUserExt.getPassword()).authorities(authorities).build();
        return userDetails;
    }
}
